/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ejb;


import helpClasses.ReportProperties;
import hibernate.Product;
import hibernate.Request;
import hibernate.RequestDAO;
import hibernate.RequestStatus;
import hibernate.User;
import hibernate.UserRole;
import java.util.Date;
import javax.ejb.LocalBean;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateful;


/**
 *
 * @author aboyko
 */
@Stateful
@LocalBean
public class RequestManager extends ManagedEJB {


    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    //@EJB 
        
    private Security security;
    private MessageManager messageManager;
    private ReportManager reportManager;
    
    @EJB
    private RequestDAO requestDAO;

    /*
     * Создаем новую заявку
     */
    public boolean create(Product product, String description) throws Exception{
        boolean result = false;
        if (security.isAuthorized()) {                       //проверяем, авторизирован ли пользователь
            Request r = requestDAO.createEmptyRequest();     //создаем чистую заявку
            r.setDescription(description);
            r.setProduct(product);
            r.setInDate(new Date());
            r.setStatus(RequestStatus.GET_IN_PROGRESS_STATUS());
            r.setUser(security.getCurrentUser());
           
            if(!checkDuplication(r)){
               result = save(r);
            }           
        } 
        return result;
    }
     
    /*
     * Сохраняем новую заявку
     */
    public boolean save(Request r) throws Exception{
        boolean result = false;
        if (security.isAuthorized()) {
            requestDAO.addAndSaveNewRequest(r);
            messageManager.sendMailSwitch(r);
            result = true;
        } 
        return result;
    }
   
    
    /*
     * Обновляем заявку
     */
    public boolean update(Request r) throws Exception{
        boolean result = false;
        if (security.isAuthorized()) {
            r.setManager(security.getCurrentUser());
            requestDAO.updateRequest(r);
            messageManager.sendMailSwitch(r);
            result = true;
        }
        return result;
    }

    
    /*
     * Проверка на дупликаты
     */
    public boolean checkDuplication(Request r) {
        boolean result = false;
        ReportProperties rp = new ReportProperties();
        rp.setStatus(RequestStatus.GET_IN_PROGRESS_STATUS());
        rp.setProduct(r.getProduct());
        if (r.getProduct().isCommon()) {
            rp.setFilterByCommon(true);
            rp.setIsCommon(true);
        } else {
            rp.setUser(security.getCurrentUser());
        }
        List<Request> l = reportManager.getRequests(rp);
        if (l != null) {
            if (!l.isEmpty()) 
                result = true;
            }
        return result;
    }

     public Request getRequestByID(int i) {
        Request r = requestDAO.getRequestByID(i);
        User u = security.getCurrentUser();
        if ((!r.getUser().equals(u)
                && u.getRole().equals(UserRole.GET_USER_ROLE())
                && !r.getProduct().isCommon())
                || !security.isAuthorized()) {
            return null;
        } else {
            return r;
        }
    }

    public List<RequestStatus> getAllRequestStatuses() {
        return requestDAO.getAllRequestStatuses();
    }

    public RequestStatus getRequestStatusByID(int id) {
        return requestDAO.getRequestStatusByID(id);
    }
    /*
     * Статус по заявке
     */
    @Deprecated
    private RequestStatus GetSatusInProgress() {
        return requestDAO.getRequestStatusByID(1);
    }

    @Deprecated
    private RequestStatus GetSatusComplit() {
        return requestDAO.getRequestStatusByID(2);
    }

    @Deprecated
    private RequestStatus GetSatusRejected() {
        return requestDAO.getRequestStatusByID(3);
    }
    // public void Create

    @Override
    public boolean init(ServerManager serverManager) {
        //Оставить этот код без изменений!
        if(!super.init(serverManager))
            return false;
        //Подключать необходимые бины ниже.
        security = serverManager.getSecurity();
        reportManager = serverManager.getReportManager();
        messageManager = serverManager.getSendingMail();
        return true;
    }
}
